﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Otgruzka.ServicesClients;
using System.Configuration;
using BusinessLogic.Security;
using Otgruzka.Controls.jQuery;
using DataTier;
using DataTier.Entities;
using System.ServiceModel;

namespace Otgruzka.Controls.Order
{
    public partial class OrderList : System.Web.UI.UserControl
    {
        /// <summary>
        /// Свойство, указывающее на наличие фильтра
        /// </summary>
        protected bool IsFiltered
        {
            get { return Session["SearchParameters"] != null && Session["SearchParameters"] is SearchParameters; }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            //new Common.Logger().LogMessage("Начало OrderList.ascx.cs Page_Load()");

            // 11.12.2012 ЗАКОММЕНТИРОВАНА ОЧИСТКА СЕССИОННЫХ ЗНАЧЕНИЙ ВЕЗДЕ, КРОМЕ КЛИКА НА КНОПКУ "ОЧИСТИТЬ ФИЛЬТРЫ"
            //if (!IsPostBack)
            //    Session["ordersNumPage"] = null;
            
            SearchParameters searchParameters = null;

            if (IsPostBack)
            {
                // Заполняется объект SearchParameters
                searchParameters = GetSearchParameters();

                // SearchParameters добавляется в сессию
                Session["SearchParameters"] = searchParameters;
            }
            else // 11.12.2012 ЗАКОММЕНТИРОВАНА ОЧИСТКА СЕССИОННЫХ ЗНАЧЕНИЙ ВЕЗДЕ, КРОМЕ КЛИКА НА КНОПКУ "ОЧИСТИТЬ ФИЛЬТРЫ"
            {
                if (Session["SearchParameters"] != null)
                    searchParameters = Session["SearchParameters"] as SearchParameters;
            }

            BindPaging(searchParameters);
            if (!IsPostBack) 
                Bind();
            FillFiltersFields();
        }


        private void BindPaging(SearchParameters searchParameters)
        {
            int? numRows = new OrdersClient().GetOrderListCount(UserPrincipal.Current.UserId, UserPrincipal.Current.OnliIts, searchParameters);
            this.PagingTop.CountRows = numRows;
            this.PagingTop.NumPageSessionName = "ordersNumPage";
            this.PagingTop.PageNumberChange += new Paging.PageNumberChangeHandler(PagingTop_PageNumberChange);

            this.PagingBottom.CountRows = numRows;
            this.PagingBottom.NumPageSessionName = "ordersNumPage";
            this.PagingBottom.PageNumberChange += new Paging.PageNumberChangeHandler(PagingBottom_PageNumberChange);
        }

        void PagingBottom_PageNumberChange(object sender, PageNumberChangeEventArgs data)
        {
            this.PagingTop.Bind();
            Bind();
            FillFiltersFields(); // Заполняются поля ввода для фильтров из Session
        }

        void PagingTop_PageNumberChange(object sender, PageNumberChangeEventArgs data)
        {
            this.PagingBottom.Bind();
            Bind();
            FillFiltersFields(); // Заполняются поля ввода для фильтров из Session
        }


        protected void btnGetOrders_Click(object sender, EventArgs e)
        {
            Bind();
        }

        protected void OrderList_Filtr_click(object sender, EventArgs e)
        {
            //// Заполняются поля ввода для фильтров из Session
            //FillFiltersFields();
            //SearchParameters searchParameters = null;
            //searchParameters = GetSearchParameters();

            //var orders = GetOrders();
            //if (orders != null && orders.Count > 0)
            //{
            //    //this.Orders.DataSource = orders.Where(o => o.Id == Convert.ToInt32(this.search_id.Text));

            //    // Номер заказа
            //    if (searchParameters.OrderNumber!=null)
            //        this.Orders.DataSource = orders.Where(o => o.Number.ToLower().Contains(searchParameters.OrderNumber.ToLower()));

            //    // Центр затрат
            //    if (searchParameters.CostsCentr != null)
            //        this.Orders.DataSource = orders.Where(o => o.CreatedCostCenterName.ToLower().Contains(searchParameters.CostsCentr.ToLower()));

            //    // Дата заказа
            //    if (searchParameters.OrderCreatedDate != null)
            //        this.Orders.DataSource = orders.Where(o => o.CreatedDate.Value.Date.ToShortDateString().Contains(searchParameters.OrderCreatedDate.Value.Date.ToShortDateString()));

            //    // Сумма заказа
            //    if (searchParameters.OrderSumm != null)
            //        this.Orders.DataSource = orders.Where(o => o.ItogoSumm == searchParameters.OrderSumm);

            //    // Номер счета
            //    if (searchParameters.AccountNumber!=null)
            //        this.Orders.DataSource = orders.Where(o => o.AccountNumber.ToLower().Contains(searchParameters.AccountNumber.ToLower()));

            //    // Дата счета
            //    if (searchParameters.AccountDate != null)
            //        this.Orders.DataSource = orders.Where(o => o.AccountCreatedDate.Value.Date.ToShortDateString().Contains(searchParameters.AccountDate.Value.Date.ToShortDateString()));

            //    this.Orders.DataBind();
            //}

            // 11.12.2012 ЗАКОММЕНТИРОВАНА ОЧИСТКА СЕССИОННЫХ ЗНАЧЕНИЙ ВЕЗДЕ, КРОМЕ КЛИКА НА КНОПКУ "ОЧИСТИТЬ ФИЛЬТРЫ"
            //Session["ordersNumPage"] = null;
            BindAndFillFiltersPaging();
        }


        /// <summary>
        /// Заполняются поля ввода для фильтров из Session
        /// </summary>
        private void FillFiltersFields()
        {
            var searchParameters = Session["SearchParameters"] as SearchParameters;
            if (searchParameters != null)
            {
                #region Заполняются поля ввода фильтров

                var HCreatedUserName = this.Orders.HeaderRow.FindControl("HCreatedUserName") as TextBox;
                var HNumber = this.Orders.HeaderRow.FindControl("HNumber") as TextBox;
                var HCreatedDepartmentName = this.Orders.HeaderRow.FindControl("HCreatedDepartmentName") as TextBox;
                var HCreatedCostCenterName = this.Orders.HeaderRow.FindControl("HCreatedCostCenterName") as TextBox;
                var HCreatedJuridicalPersonName = this.Orders.HeaderRow.FindControl("HCreatedJuridicalPersonName") as TextBox;
                var HCreatedDate = this.Orders.HeaderRow.FindControl("HCreatedDate") as jQuery.JQueryDatepicker; //var HCreatedDate = this.Orders.HeaderRow.FindControl("HCreatedDate") as TextBox;
                var HItogoSumm = this.Orders.HeaderRow.FindControl("HItogoSumm") as TextBox;
                var HStateName = this.Orders.HeaderRow.FindControl("HStateName") as TextBox;
                var HAccountNumber = this.Orders.HeaderRow.FindControl("HAccountNumber") as TextBox;
                var HAccountCreatedDate = this.Orders.HeaderRow.FindControl("HAccountCreatedDate") as jQuery.JQueryDatepicker;

                if (HCreatedUserName != null)
                    HCreatedUserName.Text = searchParameters.OrderCreatedUser;

                if (HNumber != null)
                    HNumber.Text = searchParameters.OrderNumber;

                if (HCreatedDepartmentName != null)
                    HCreatedDepartmentName.Text = searchParameters.Department;

                if (HCreatedCostCenterName != null)
                    HCreatedCostCenterName.Text = searchParameters.CostsCentr;

                if (HCreatedJuridicalPersonName != null)
                    HCreatedJuridicalPersonName.Text = searchParameters.JuridicalPerson;

                if (HCreatedDate != null)
                    HCreatedDate.SelectedDate = searchParameters.OrderCreatedDate;

                if (HItogoSumm != null)
                    HItogoSumm.Text = (searchParameters.OrderSumm.HasValue) ? searchParameters.OrderSumm.Value.ToString().Replace(",",".") : "";

                if (HStateName != null)
                    HStateName.Text = searchParameters.OrderStatus;

                if (HAccountNumber != null)
                    HAccountNumber.Text = searchParameters.AccountNumber;

                if (HAccountCreatedDate != null)
                    HAccountCreatedDate.SelectedDate = searchParameters.AccountDate;

                #endregion Заполняются поля ввода фильтров
            }
        }


        /// <summary>
        /// Возвращается объект SearchParameters формирующийся из полей ввода фильтров
        /// </summary>
        /// <returns></returns>
        private SearchParameters GetSearchParameters()
        {
            // Создаем экземпляр SearchParameters
            SearchParameters searchParameters = new SearchParameters();

            #region Заполняется объект SearchParameters

            var HCreatedUserName = this.Orders.HeaderRow.FindControl("HCreatedUserName") as TextBox;
            var HNumber = this.Orders.HeaderRow.FindControl("HNumber") as TextBox;
            var HCreatedDepartmentName = this.Orders.HeaderRow.FindControl("HCreatedDepartmentName") as TextBox;
            var HCreatedCostCenterName = this.Orders.HeaderRow.FindControl("HCreatedCostCenterName") as TextBox;
            var HCreatedJuridicalPersonName = this.Orders.HeaderRow.FindControl("HCreatedJuridicalPersonName") as TextBox;
            var HCreatedDate = this.Orders.HeaderRow.FindControl("HCreatedDate") as jQuery.JQueryDatepicker; //var HCreatedDate = this.Orders.HeaderRow.FindControl("HCreatedDate") as TextBox;
            var HItogoSumm = this.Orders.HeaderRow.FindControl("HItogoSumm") as TextBox;
            var HStateName = this.Orders.HeaderRow.FindControl("HStateName") as TextBox;
            var HAccountNumber = this.Orders.HeaderRow.FindControl("HAccountNumber") as TextBox;
            var HAccountCreatedDate = this.Orders.HeaderRow.FindControl("HAccountCreatedDate") as jQuery.JQueryDatepicker;

            if (HCreatedUserName != null && !string.IsNullOrEmpty(HCreatedUserName.Text))
                searchParameters.OrderCreatedUser = HCreatedUserName.Text;

            if (HNumber != null && !string.IsNullOrEmpty(HNumber.Text))
                searchParameters.OrderNumber = HNumber.Text;

            if (HCreatedDepartmentName != null && !string.IsNullOrEmpty(HCreatedDepartmentName.Text))
                searchParameters.Department = HCreatedDepartmentName.Text;

            if (HCreatedCostCenterName != null && !string.IsNullOrEmpty(HCreatedCostCenterName.Text))
                searchParameters.CostsCentr = HCreatedCostCenterName.Text;

            if (HCreatedJuridicalPersonName != null && !string.IsNullOrEmpty(HCreatedJuridicalPersonName.Text))
                searchParameters.JuridicalPerson = HCreatedJuridicalPersonName.Text;

            if (HCreatedDate != null && HCreatedDate.SelectedDate.HasValue)
                searchParameters.OrderCreatedDate = HCreatedDate.SelectedDate.Value;

            if (HItogoSumm != null && !string.IsNullOrEmpty(HItogoSumm.Text))
                //searchParameters.OrderSumm = Convert.ToDouble(HItogoSumm.Text.Replace(',', '.'));
                searchParameters.OrderSumm = HItogoSumm.Text.GetDoubleFromString();


            if (HStateName != null && !string.IsNullOrEmpty(HStateName.Text))
                searchParameters.OrderStatus = HStateName.Text;

            if (HAccountNumber != null && !string.IsNullOrEmpty(HAccountNumber.Text))
                searchParameters.AccountNumber = HAccountNumber.Text;

            if (HAccountCreatedDate != null && HAccountCreatedDate.SelectedDate.HasValue)
                searchParameters.AccountDate = HAccountCreatedDate.SelectedDate.Value;


            // Если все поля с фильтрами пустые, то объект с параметрами приравнивается NULL
            if ((HCreatedUserName == null || string.IsNullOrEmpty(HCreatedUserName.Text)) &&
                (HNumber == null || string.IsNullOrEmpty(HNumber.Text)) &&
                (HCreatedDepartmentName == null || string.IsNullOrEmpty(HCreatedDepartmentName.Text)) &&
                (HCreatedCostCenterName == null || string.IsNullOrEmpty(HCreatedCostCenterName.Text)) &&
                (HCreatedJuridicalPersonName == null || string.IsNullOrEmpty(HCreatedJuridicalPersonName.Text)) &&
                (HCreatedDate == null || !HCreatedDate.SelectedDate.HasValue) &&
                (HItogoSumm == null || string.IsNullOrEmpty(HItogoSumm.Text)) &&
                (HStateName == null || string.IsNullOrEmpty(HStateName.Text)) &&
                (HAccountNumber == null || string.IsNullOrEmpty(HAccountNumber.Text)) &&
                (HAccountCreatedDate == null || !HAccountCreatedDate.SelectedDate.HasValue)
            )
            {
                searchParameters = null;// searchParameters = (Session["SearchParameters"] != null) ? Session["SearchParameters"] as SearchParameters : null;
            }

            #endregion Заполняется объект SearchParameters
            { }
            return searchParameters;
        }


        protected void OrderList_Clear_Filtr(object sender, EventArgs e)
        {
            Session["SearchParameters"] = null;
            this.PagingTop.CurrentPageNumber = 1;
            this.PagingBottom.CurrentPageNumber = 1;
            Session["SortDirection"] = null;
            Session["SortExpression"] = null;
            Response.Redirect("~/WebForms/OrderList.aspx");
        }

        private void Bind()
        {
            var orders = GetOrders();

            if (orders != null)
                this.Orders.DataSource = orders.ToList();

            this.Orders.DataBind();

        }

        private List<OrderFullInfoEntity> GetOrders(string sortExpression = null, string direction = null)
        {
            //if (string.IsNullOrEmpty(direction) && ViewState["SortDirection"] != null)
            //    direction = ViewState["SortDirection"].ToString();
            //if (string.IsNullOrEmpty(sortExpression) && ViewState["SortExpression"] != null)
            //    sortExpression = ViewState["SortExpression"].ToString();
            if (string.IsNullOrEmpty(direction) && Session["SortDirection"] != null)
                direction = Session["SortDirection"].ToString();
            if (string.IsNullOrEmpty(sortExpression) && Session["SortExpression"] != null)
                sortExpression = Session["SortExpression"].ToString();

            var client = new OrdersClient();
            try
            {
                int numPage = this.PagingTop.CurrentPageNumber;
                int onPage = (ConfigurationManager.AppSettings["RowsOnPage"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["RowsOnPage"]) : 11;

                var searchParameters = (Session["SearchParameters"] != null) ? Session["SearchParameters"] as SearchParameters : null;
                var orders = client.GetOrderList(UserPrincipal.Current.UserId, UserPrincipal.Current.OnliIts, numPage, onPage, searchParameters, sortExpression, direction);

                return orders;
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
                return null;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
                return null;
            }
        }


        protected void Orders_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int id = Convert.ToInt32(Orders.SelectedRow.Cells[0].Text);
                Response.Redirect(string.Format("~/WebForms/OrderDetails.aspx?oid={0}", id));
            }
            catch (Exception ex)
            { }
        }


        /// <summary>
        /// Событие заполнения строки грида данными
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Orders_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int OrderId = 0;
                var BackColor = System.Drawing.Color.White;
                string rowColor = string.Empty;
                var dataItem = e.Row.DataItem as OrderFullInfoEntity;
                if (dataItem != null)
                {
                    //rowColor = (dataItem.AccountId.HasValue) ? dataItem.AccountStateColor : dataItem.StateColor;
                    rowColor = dataItem.StateColor;
                    OrderId = dataItem.Id;
                }

                try
                {
                    BackColor = (dataItem.ExistsIsUnavailable) ? System.Drawing.Color.Red : System.Drawing.Color.FromName(rowColor);
                }
                catch (Exception ex)
                { }
                e.Row.BackColor = BackColor;

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='#6b8cbe'";
                    e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='" + BackColor.Name + "'";
                    e.Row.Attributes["style"] = "cursor:hand;";

                    #region // старый вариант одинарного клика: редирект через JavaScript
                    //if (OrderId > 0)
                    //{
                    //    string url = ResolveUrl(string.Format("~/WebForms/OrderDetails.aspx?oid={0}", OrderId));
                    //    e.Row.Attributes["onClick"] = string.Format("location.href='{0}'", url);
                    //}
                    #endregion // старый вариант одинарного клика: редирект через JavaScript

                    #region // старый вариант одинарного клика: инициация клика на кнопку реактирования в строке
                    //var button = e.Row.FindControl("EditButton") as LinkButton;
                    //if (button != null)
                    //{
                    //    button.CommandArgument = OrderId.ToString();
                    //    e.Row.Attributes["onClick"] = string.Format("javascript: {0}.click();", button.ClientID);
                    //}
                    #endregion // старый вариант одинарного клика: инициация клика на кнопку реактирования в строке

                    var grid = sender as GridView;
                    string postback = Page.ClientScript.GetPostBackEventReference(grid, string.Format("Select${0}", e.Row.RowIndex));
                    e.Row.Attributes.Add("onclick", postback.ToString());
                }
            }
        }


        /// <summary>
        /// Событие нажатия на LinkButton для редактирования Заказа
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EditButton_Click(object sender, EventArgs e)
        {
            try
            {
                int oid = Convert.ToInt32((sender as LinkButton).CommandArgument);
                Response.Redirect(string.Format("~/WebForms/OrderDetails.aspx?oid={0}", oid));
            }
            catch(Exception ex)
            { }
        }


        protected void HeaderColumn_Click(object sender, EventArgs e)
        {
            //var button = sender as LinkButton;
            //if (button != null && button.CommandName.Equals("Sort"))
            //{
            //    string column = button.CommandArgument.ToString();
            //    string direction = GetSortDirection(column);
            //    Sorting(column, direction);
            //}
        }

        private void SortOrdersGridView(string sortExpression, string direction)
        {
            var orders = GetOrders(sortExpression, direction);
            Orders.DataSource = orders;
            Orders.DataBind();
        }

        private void SortOrdersGridView(string sortExpression, SortDirection direction)
        {
            var orders = GetOrders();
            if (orders != null && orders.Count > 0)
            {
                if (sortExpression == "Id")
                {
                    if (direction == SortDirection.Ascending)
                        Orders.DataSource = orders.OrderBy(o => o.Id);
                    else
                        Orders.DataSource = orders.OrderByDescending(o => o.Id);
                }
                else if (sortExpression == "ItogoSumm")
                {
                    if (direction == SortDirection.Ascending)
                        Orders.DataSource = orders.OrderBy(o => o.ItogoSumm);
                    else
                        Orders.DataSource = orders.OrderByDescending(o => o.ItogoSumm);
                }
                else if (sortExpression == "CreatedDate")
                {
                    if (direction == SortDirection.Ascending)
                        Orders.DataSource = orders.OrderBy(o => o.CreatedDate);
                    else
                        Orders.DataSource = orders.OrderByDescending(o => o.CreatedDate);
                }
                else if (sortExpression == "StateName")
                {
                    if (direction == SortDirection.Ascending)
                        Orders.DataSource = orders.OrderBy(o => o.StateName);
                    else
                        Orders.DataSource = orders.OrderByDescending(o => o.StateName);
                }
                Orders.DataBind();
            }
        }

        protected void Orders_Sorting(object sender, GridViewSortEventArgs e)
        {
            string direction = e.SortDirection.ToString().Substring(0,3).ToLower();
            string column = e.SortExpression.ToString();
            Sorting(column, direction);

            FillFiltersFields();
        }

        private void Sorting(string SortExpression, string SortDirection)
        {
            //string column = "";
            //string direction = GetSortDirection(column);
            //SortOrdersGridView(column, direction);
            //SortOrdersGridView(e.SortExpression, e.SortDirection);

            string direction = SortDirection.ToString().Substring(0, 3).ToLower();
            string column = SortExpression.ToString();
            try
            {
                if (Session["OrderList_" + column].ToString() == direction) Session["OrderList_" + column] = "desc";
                else Session["OrderList_" + column] = "asc";
            }
            catch (Exception)
            {
                Session["OrderList_" + column] = "asc";
            }

            //ViewState["SortDirection"] = Session["OrderList_" + column].ToString();
            //ViewState["SortExpression"] = column;
            Session["SortDirection"] = Session["OrderList_" + column].ToString();
            Session["SortExpression"] = column;

            SortOrdersGridView(column, Session["OrderList_" + column].ToString());
        }

        private string GetSortDirection(string column)
        {

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            //string sortExpression = ViewState["SortExpression"] as string;
            string sortExpression = Session["SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted. Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    //string lastDirection = ViewState["SortDirection"] as string;
                    string lastDirection = Session["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            //ViewState["SortDirection"] = sortDirection;
            //ViewState["SortExpression"] = column;
            Session["SortDirection"] = sortDirection;
            Session["SortExpression"] = column;

            return sortDirection;
        }


        private void BindAndFillFiltersPaging()
        {
            SearchParameters searchParameters = null;
            searchParameters = GetSearchParameters();
            BindPaging(searchParameters);
            Bind();
            FillFiltersFields();
        }


    }
}
